{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Converting a trained model to tflite\n",
    "https://www.tensorflow.org/lite/microcontrollers/build_convert#model_conversion"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Convert model to tflite"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import tensorflow as tf\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "training_spectrogram = np.load('training_spectrogram.npz')\n",
    "validation_spectrogram = np.load('validation_spectrogram.npz')\n",
    "test_spectrogram = np.load('test_spectrogram.npz')\n",
    "\n",
    "X_train = training_spectrogram['X']\n",
    "X_validate = validation_spectrogram['X']\n",
    "X_test = test_spectrogram['X']\n",
    "\n",
    "complete_train_X = np.concatenate((X_train, X_validate, X_test))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "44128"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "converter2 = tf.lite.TFLiteConverter.from_saved_model(\"fully_trained.model\")\n",
    "converter2.optimizations = [tf.lite.Optimize.DEFAULT]\n",
    "def representative_dataset_gen():\n",
    "    for i in range(0, len(complete_train_X), 100):\n",
    "        # Get sample input data as a numpy array in a method of your choosing.\n",
    "        yield [complete_train_X[i:i+100]]\n",
    "converter2.representative_dataset = representative_dataset_gen\n",
    "# converter.optimizations = [tf.lite.Optimize.OPTIMIZE_FOR_SIZE]\n",
    "converter2.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]\n",
    "tflite_quant_model = converter2.convert()\n",
    "open(\"converted_model.tflite\", \"wb\").write(tflite_quant_model)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# To convert to C++\n",
    "This will run a command line too to convert out tflite model into C code."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "!xxd -i converted_model.tflite > model_data.cc"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
